package com.iflytek.aidemo.student;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.text.InputType;
import android.os.Build;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.Editable;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.DisplayMetrics;

import androidx.appcompat.app.AppCompatActivity;

import com.iflytek.aidemo.R;
import com.iflytek.aidemo.model.WrongQuestionRecord;

import java.util.ArrayList;
import java.util.List;

public class WrongQuestionPracticeActivity extends AppCompatActivity {
    private TextView questionText;
    private TextView timerText;
    private TextView progressText;
    private Button submitButton;
    private Button clearButton;
    private Button prevButton;
    private ImageView backButton;
    private ImageView answerPreview;
    private EditText answerInput;
    private TextView answerCorrectLabel;

    // 数字输入相关
    private List<String> answerTexts = new ArrayList<>();
    // 每题的验证颜色（null 表示未验证；Color.GREEN/Color.RED 表示验证后的颜色应保持）
    private List<Integer> answerColors = new ArrayList<>();
    // 每题是否已答对并锁定（true 表示该题已正确，禁改）
    private List<Boolean> answerLocked = new ArrayList<>();
    // 文本变化监听的抑制与上一次长度
    private boolean suppressWatcher = false;
    private int watcherOldLen = 0;

    private WrongQuestionRecord currentQuestion;
    private int currentQuestionIndex = 0;
    private List<WrongQuestionRecord> questionList;

    // 练习计时
    private long startMs = 0L;
    private Handler timerHandler = new Handler();
    private final Runnable timerRunnable = new Runnable() {
        @Override
        public void run() {
            if (timerText != null && startMs > 0) {
                long elapsed = System.currentTimeMillis() - startMs;
                timerText.setText(formatDuration(elapsed));
                timerHandler.postDelayed(this, 1000);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        try {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_wrong_question_practice);
            initViews();

            loadQuestions();

            // 启动计时
            startMs = System.currentTimeMillis();
            timerHandler.post(timerRunnable);

        } catch (Exception e) {
            System.out.println("WrongQuestionPracticeActivity onCreate 异常: " + e.getMessage());
            e.printStackTrace();
            Toast.makeText(this, "初始化练习界面失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    private void initViews() {
        try {
            questionText = findViewById(R.id.question_text);
            timerText = findViewById(R.id.timer_text);
            progressText = findViewById(R.id.progress_text);
            submitButton = findViewById(R.id.submit_button);
            clearButton = findViewById(R.id.clear_button);
            prevButton = findViewById(R.id.prev_button);
            backButton = findViewById(R.id.back_button);
            answerPreview = findViewById(R.id.answer_preview);
            answerInput = findViewById(R.id.answer_input);
            answerCorrectLabel = findViewById(R.id.answer_correct_label);

            // 检查是否有任何视图为null
            if (questionText == null || timerText == null || progressText == null ||
                    submitButton == null || clearButton == null || prevButton == null || backButton == null ||
                    answerPreview == null || answerInput == null || answerCorrectLabel == null) {
                throw new RuntimeException("某些视图未找到");
            }

            // 禁用系统软键盘，使用固定数字键盘
            answerInput.setInputType(InputType.TYPE_NULL);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                answerInput.setShowSoftInputOnFocus(false);
            }

            // 绑定数字键盘点击事件
            int[] numIds = new int[]{
                    R.id.key_0, R.id.key_1, R.id.key_2, R.id.key_3, R.id.key_4,
                    R.id.key_5, R.id.key_6, R.id.key_7, R.id.key_8, R.id.key_9
            };
            String[] numTexts = new String[]{"0","1","2","3","4","5","6","7","8","9"};
            for (int i = 0; i < numIds.length; i++) {
                final String t = numTexts[i];
                View v = findViewById(numIds[i]);
                if (v != null) v.setOnClickListener(view -> appendToInput(t));
            }
            View keyDot = findViewById(R.id.key_dot);
            if (keyDot != null) keyDot.setOnClickListener(v -> appendToInput("."));
            View keyDel = findViewById(R.id.key_del);
            if (keyDel != null) keyDel.setOnClickListener(v -> deleteLastChar());
            View keyOk = findViewById(R.id.key_ok);
            if (keyOk != null) keyOk.setOnClickListener(v -> validateAnswer());

            // 清除按钮
            clearButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (isLocked(currentQuestionIndex)) {
                        Toast.makeText(WrongQuestionPracticeActivity.this, "本题已验证正确，无法修改", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (answerInput != null) {
                        answerInput.setText("");
                    }
                    answerPreview.setImageDrawable(null);
                    saveInputForCurrent("");
                    // 清除时同时重置颜色状态，后续输入恢复黑色直到再次验证
                    saveColorForCurrent(null);
                }
            });

            // 监听输入框文本变化，捕捉系统键盘删除等行为
            if (answerInput != null) {
                answerInput.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                        watcherOldLen = s != null ? s.length() : 0;
                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        if (suppressWatcher) return;
                        int newLen = s != null ? s.length() : 0;
                        if (newLen < watcherOldLen) {
                            // 检测到删除，重置颜色并用黑色预览
                            saveColorForCurrent(null);
                            String txt = s != null ? s.toString() : "";
                            if (!TextUtils.isEmpty(txt)) {
                                drawTextToPreview(txt);
                            } else {
                                answerPreview.setImageDrawable(null);
                            }
                        }
                    }

                    @Override
                    public void afterTextChanged(Editable s) { }
                });
            }

            // 上一题按钮
            prevButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (currentQuestionIndex > 0) {
                        showQuestion(currentQuestionIndex - 1);
                    } else {
                        Toast.makeText(WrongQuestionPracticeActivity.this, "已经是第一题了", Toast.LENGTH_SHORT).show();
                    }
                }
            });

            // 提交按钮
            submitButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    submitAnswer();
                }
            });

            // 返回按钮
            backButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });

            System.out.println("视图初始化完成");
        } catch (Exception e) {
            System.out.println("initViews 异常: " + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }

    private void loadQuestions() {
        try {
            // 从Intent获取错题列表
            Intent intent = getIntent();
            if (intent != null) {
                // 1) 优先尝试：直接传入题目与答案（多题）
                ArrayList<String> questionsExtra = intent.getStringArrayListExtra("questions");
                ArrayList<String> answersExtra = intent.getStringArrayListExtra("answers");
                ArrayList<Integer> idsExtra = intent.getIntegerArrayListExtra("wrong_question_ids");
                if (questionsExtra != null && answersExtra != null && !questionsExtra.isEmpty() && questionsExtra.size() == answersExtra.size()) {
                    questionList = new ArrayList<>();
                    for (int i = 0; i < questionsExtra.size(); i++) {
                        WrongQuestionRecord record = new WrongQuestionRecord();
                        // 若传入了wrong_question_ids并长度匹配，则使用该ID，否则用索引作为占位
                        if (idsExtra != null && idsExtra.size() == questionsExtra.size()) {
                            record.setWrongId(idsExtra.get(i));
                        } else {
                            record.setWrongId(i);
                        }
                        record.setQuestion(questionsExtra.get(i));
                        record.setAnswer(answersExtra.get(i));
                        questionList.add(record);
                    }
                    showQuestion(0);
                    return;
                }

                // 2) 尝试：直接传入单题（question/answer）
                String qSingle = intent.getStringExtra("question");
                String aSingle = intent.getStringExtra("answer");
                ArrayList<Integer> idsSingle = intent.getIntegerArrayListExtra("wrong_question_ids");
                if (!TextUtils.isEmpty(qSingle) && !TextUtils.isEmpty(aSingle)) {
                    questionList = new ArrayList<>();
                    WrongQuestionRecord record = new WrongQuestionRecord();
                    if (idsSingle != null && !idsSingle.isEmpty()) {
                        record.setWrongId(idsSingle.get(0));
                    } else {
                        record.setWrongId(0);
                    }
                    record.setQuestion(qSingle);
                    record.setAnswer(aSingle);
                    questionList.add(record);
                    showQuestion(0);
                }
            }
        } catch (Exception e) {
            System.out.println("loadQuestions 异常: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private void showQuestion(int index) {
        try {
            if (index >= 0 && index < questionList.size()) {
                // 切换前保存当前题目的输入文本
                if (answerInput != null) {
                    saveInputForCurrent(answerInput.getText() != null ? answerInput.getText().toString() : "");
                }

                currentQuestionIndex = index;
                currentQuestion = questionList.get(index);

                // 显示题干（使用 question 字段）
                String stem = currentQuestion.getQuestion();
                if (TextUtils.isEmpty(stem)) stem = "";
                questionText.setText("题目 " + (index + 1) + ": " + stem);

                // 更新进度
                progressText.setText((index + 1) + "/" + questionList.size());

                // 根据题目位置更新按钮状态
                if (index == 0) {
                    prevButton.setEnabled(false);
                    prevButton.setAlpha(0.5f);
                } else {
                    prevButton.setEnabled(true);
                    prevButton.setAlpha(1.0f);
                }

                if (index == questionList.size() - 1) {
                    submitButton.setText("提交");
                } else {
                    submitButton.setText("下一题");
                }

                // 回显该题已保存的输入并刷新预览
                String text = getInputFor(index);
                if (answerInput != null) {
                    suppressWatcher = true;
                    answerInput.setText(text != null ? text : "");
                    answerInput.setSelection(answerInput.getText().length());
                    suppressWatcher = false;
                }
                // 锁定/解锁视图状态
                boolean locked = isLocked(index);
                if (locked) {
                    answerInput.setVisibility(View.GONE);
                    answerCorrectLabel.setVisibility(View.VISIBLE);
                } else {
                    answerInput.setVisibility(View.VISIBLE);
                    answerCorrectLabel.setVisibility(View.GONE);
                }
                if (!TextUtils.isEmpty(text)) {
                    Integer c = getColorFor(index);
                    if (c != null) {
                        drawColoredPreview(text, c);
                    } else {
                        drawTextToPreview(text);
                    }
                } else {
                    answerPreview.setImageDrawable(null);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //提交/下一题：最后一题时汇总并跳转结果页
    private void submitAnswer() {
        try {
            String input = answerInput.getText() != null ? answerInput.getText().toString().trim() : "";
            // 提交前保存当前题目的输入文本
            if (answerInput != null) {
                saveInputForCurrent(answerInput.getText() != null ? answerInput.getText().toString() : "");
            }

            if (currentQuestionIndex == questionList.size() - 1) {
                // 最后一题：直接汇总（未验证的自动验证）并跳转结果页
                computeAndFinish();
            } else {
                // 进入下一题
                showQuestion(currentQuestionIndex + 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 验证
    private void validateAnswer() {
        if (answerInput == null || currentQuestion == null) return;
        String input = answerInput.getText() != null ? answerInput.getText().toString().trim() : "";
        if (TextUtils.isEmpty(input)) {
            Toast.makeText(this, "请先输入答案", Toast.LENGTH_SHORT).show();
            return;
        }
        saveInputForCurrent(input);

        String right = currentQuestion.getAnswer();
        String normIn = normalize(input);
        String normAns = normalize(right);

        if (!TextUtils.isEmpty(normAns) && normIn.equals(normAns)) {
            // 正确：结果预览为绿色
            saveColorForCurrent(Color.GREEN);
            drawColoredPreview(input, Color.GREEN);
            // 锁定该题并隐藏输入，显示“该题回答正确”
            saveLockedForCurrent(true);
            answerInput.setVisibility(View.GONE);
            if (answerCorrectLabel != null) answerCorrectLabel.setVisibility(View.VISIBLE);
            if (currentQuestionIndex == questionList.size() - 1) {
                //Toast.makeText(this, "验证正确，练习完成！", Toast.LENGTH_SHORT).show();
                //submitAnswer();
            } else {
                //Toast.makeText(this, "验证正确，进入下一题", Toast.LENGTH_SHORT).show();
                //showQuestion(currentQuestionIndex + 1);
            }
        } else {
            Toast.makeText(this, "回答不正确，再好好想想^-^", Toast.LENGTH_SHORT).show();
            // 错误：结果预览为红色
            saveColorForCurrent(Color.RED);
            drawColoredPreview(input, Color.RED);
        }
    }

    private String normalize(String s) {
        if (s == null) return "";
        return s.replace(" ", "").replace("\u00A0", "").trim();
    }

    private void drawTextToPreview(String text) {
        if (answerPreview == null) return;
        answerPreview.setVisibility(View.VISIBLE);
        int size = dp(64); // 预览框大小
        Bitmap bmp = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bmp);

        // 白色背景
        canvas.drawColor(Color.WHITE);

        // 绘制文字
        Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
        p.setColor(Color.BLACK);
        p.setTextAlign(Paint.Align.CENTER);
        p.setTextSize(dp(20));

        // 垂直居中
        Paint.FontMetrics fm = p.getFontMetrics();
        float x = size / 2f;
        float y = size / 2f - (fm.ascent + fm.descent) / 2f;
        canvas.drawText(text, x, y, p);

        answerPreview.setImageBitmap(bmp);
        answerPreview.setVisibility(View.VISIBLE);
    }

    // 用于验证结果的彩色预览
    private void drawColoredPreview(String text, int color) {
        if (answerPreview == null) return;
        answerPreview.setVisibility(View.VISIBLE);
        int size = dp(64);
        Bitmap bmp = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bmp);

        canvas.drawColor(Color.WHITE);

        Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
        p.setColor(color);
        p.setTextAlign(Paint.Align.CENTER);
        p.setTextSize(dp(20));

        Paint.FontMetrics fm = p.getFontMetrics();
        float x = size / 2f;
        float y = size / 2f - (fm.ascent + fm.descent) / 2f;
        canvas.drawText(text, x, y, p);

        answerPreview.setImageBitmap(bmp);
        answerPreview.setVisibility(View.VISIBLE);
    }

    private int dp(int dp) {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        return Math.round(dp * dm.density);
    }

    // 追加一个字符到输入框（供自定义数字键盘使用）
    private void appendToInput(String s) {
        if (isLocked(currentQuestionIndex)) {
            Toast.makeText(this, "本题已验证正确，无法修改", Toast.LENGTH_SHORT).show();
            return;
        }
        if (answerInput == null || s == null) return;
        String cur = answerInput.getText() != null ? answerInput.getText().toString() : "";
        // 只允许出现一个小数点
        if (".".equals(s) && cur.contains(".")) {
            return;
        }
        String next = cur + s;
        answerInput.setText(next);
        answerInput.setSelection(next.length());
        saveInputForCurrent(next);
        // 实时刷新预览为黑色
        if (!TextUtils.isEmpty(next)) {
            drawTextToPreview(next);
        } else {
            answerPreview.setImageDrawable(null);
        }
    }

    private void deleteLastChar() {
        if (isLocked(currentQuestionIndex)) {
            Toast.makeText(this, "本题已验证正确，无法修改", Toast.LENGTH_SHORT).show();
            return;
        }
        if (answerInput == null) return;
        CharSequence cs = answerInput.getText();
        if (cs == null) return;
        String cur = cs.toString();
        if (cur.length() == 0) return;
        String next = cur.substring(0, cur.length() - 1);
        answerInput.setText(next);
        answerInput.setSelection(next.length());
        saveInputForCurrent(next);
        // 删除即认为答案被修改，重置颜色状态
        saveColorForCurrent(null);
        // 实时刷新预览
        if (!TextUtils.isEmpty(next)) {
            drawTextToPreview(next);
        } else {
            answerPreview.setImageDrawable(null);
        }
    }

    // 保存/读取每题的文本答案
    private void saveInputForCurrent(String text) {
        if (questionList == null || questionList.isEmpty()) return;
        while (answerTexts.size() < questionList.size()) {
            answerTexts.add(null);
        }
        answerTexts.set(currentQuestionIndex, text);
    }

    private String getInputFor(int index) {
        if (index < 0 || index >= answerTexts.size()) return null;
        return answerTexts.get(index);
    }

    // 颜色状态的保存/读取
    private void saveColorForCurrent(Integer color) {
        if (questionList == null || questionList.isEmpty()) return;
        while (answerColors.size() < questionList.size()) {
            answerColors.add(null);
        }
        answerColors.set(currentQuestionIndex, color);
    }

    private Integer getColorFor(int index) {
        if (index < 0 || index >= answerColors.size()) return null;
        return answerColors.get(index);
    }

    // 锁定状态的保存/读取
    private void saveLockedForCurrent(boolean locked) {
        if (questionList == null || questionList.isEmpty()) return;
        while (answerLocked.size() < questionList.size()) {
            answerLocked.add(false);
        }
        answerLocked.set(currentQuestionIndex, locked);
    }

    private boolean isLocked(int index) {
    if (index < 0 || index >= answerLocked.size()) return false;
    Boolean b = answerLocked.get(index);
    return b != null && b;
    }

    @Override
    protected void onDestroy() {
    super.onDestroy();
    // 停止计时回调，避免泄漏
    if (timerHandler != null) timerHandler.removeCallbacksAndMessages(null);
    }

    // 结束本次练习，统计并跳转结果页
    private void computeAndFinish() {
    try {
        if (questionList == null || questionList.isEmpty()) {
            finish();
            return;
        }
        int correct = 0;
        ArrayList<String> questions = new ArrayList<>();
        ArrayList<String> rightAnswers = new ArrayList<>();
        ArrayList<String> userAnswers = new ArrayList<>();
        boolean[] correctFlags = new boolean[questionList.size()];
        for (int i = 0; i < questionList.size(); i++) {
            WrongQuestionRecord r = questionList.get(i);
            questions.add(r.getQuestion());
            rightAnswers.add(r.getAnswer());
            boolean locked = isLocked(i);
            String userIn = getInputFor(i);
            String normIn = normalize(userIn == null ? "" : userIn);
            String normAns = normalize(r.getAnswer());
            boolean isCorrect;
            if (locked) {
                isCorrect = true;
            } else {
                //正确或者错误
                isCorrect = !TextUtils.isEmpty(normAns) && normIn.equals(normAns);
            }
            if (isCorrect) correct++;
            correctFlags[i] = isCorrect;
            userAnswers.add(userIn == null ? "" : userIn);
        }

        long elapsed = Math.max(0, System.currentTimeMillis() - startMs);
        if (timerHandler != null) timerHandler.removeCallbacksAndMessages(null);

        Intent intent = new Intent(this, WrongPracticeResultActivity.class);
    intent.putExtra("correct_count", correct);
    intent.putExtra("total_count", questionList.size());
    intent.putExtra("elapsed_ms", elapsed);
    intent.putStringArrayListExtra("questions", questions);
    intent.putStringArrayListExtra("answers", rightAnswers);
    intent.putStringArrayListExtra("user_answers", userAnswers);
    intent.putExtra("correct_flags", correctFlags);
    // 透传 from_push
    boolean fromPush = getIntent() != null && getIntent().getBooleanExtra("from_push", false);
    intent.putExtra("from_push", fromPush);
//    // 收集错题ID并传递，便于结果页执行删除/完成
//    ArrayList<Integer> ids = new ArrayList<>();
//    for (WrongQuestionRecord r : questionList) {
//        if (r != null && r.getWrongId() != null && r.getWrongId() > 0) ids.add(r.getWrongId());
//    }
//    intent.putIntegerArrayListExtra("wrong_question_ids", ids);
    startActivity(intent);
    finish();
} catch (Exception e) {
    e.printStackTrace();
    finish();
}
}


    // mm:ss 或 ss 格式
    private String formatDuration(long ms) {
    long sec = ms / 1000;
    long m = sec / 60;
    long s = sec % 60;
    if (m > 0) return m + ":" + (s < 10 ? ("0" + s) : s);
    return s + "s";
    }
}